﻿using System.ComponentModel;
using System.Windows.Forms;
using Greg.XmlEditor.Presentation.Presenters;
using System;

namespace Greg.XmlEditor.Presentation.Views
{
	public partial class DocumentView : UserControl
	{
		public DocumentView()
		{
			this.InitializeComponent();
			this.UpdateView();
		}

		public XmlTextEditor Editor
		{
			get { return this.editor; }
		}

		private DocumentPresenterBase presenter;
		public DocumentPresenterBase Presenter
		{
			get { return this.presenter; }
			set
			{
				if (this.presenter != null)
				{
					this.presenter.PropertyChanged -= OnDocumentPropertyChanged;
				}

				if (value == this.presenter) return;
				this.presenter = value;
				this.editor.Presenter = value;
				this.UpdateView();

				if (this.presenter != null)
				{
					this.presenter.PropertyChanged += OnDocumentPropertyChanged;
				}
			}
		}

		private void OnDocumentPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			switch (e.PropertyName)
			{
				case "Output":
					this.UpdateOutput();
					break;
			}
		}

		private void UpdateView()
		{
			if (this.Presenter == null)
			{
				this.editor.Enabled = false;
				this.container.Panel2Collapsed = true;
			}
			else
			{
				this.editor.IsReadOnly = !(this.presenter is DocumentPresenter);
				this.editor.Enabled = true;
				//this.editor.Text = string.IsNullOrEmpty(this.Presenter.Text) ? Environment.NewLine : this.Presenter.Text;
				this.editor.Text = this.Presenter.Text;
				this.editor.Refresh();
				this.container.Panel2Collapsed = false;
				this.UpdateOutput();
			}
		}

		private void UpdateOutput()
		{
			if (this.InvokeRequired)
			{
				this.Invoke(new Action(UpdateOutput));
			}
			else
			{
				this.output.Text = this.Presenter.Output;
			}
		}
	}
}
